package com.example.greetingcard

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

class DiceRollerActivity {

    @Preview(showBackground = true)
    @Composable
    fun DiceRollerPreview() {
        DiceWithButtonAndImage()
    }

    @Composable
    fun DiceWithButtonAndImage(modifier: Modifier = Modifier
        .fillMaxSize()
        .wrapContentSize(Alignment.Center)) {

        // 默认情况下，可组合项是无状态的，这意味着它们不存储值，并且可随时被系统重组，从而导致值被重置。
        // 可组合函数可以使用 remember 可组合项将对象存储在内存中。
        // mutableStateOf() 函数会返回一个可观察对象
        // 意味着，当 result 变量的值变化时，系统会触发重组、反映结果值并刷新界面。
        var result by remember { mutableStateOf(1) }

        Column(
            modifier = modifier,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            val imageResource = when (result) {
                1 -> R.drawable.dice_1
                2 -> R.drawable.dice_2
                3 -> R.drawable.dice_3
                4 -> R.drawable.dice_4
                5 -> R.drawable.dice_5
                else -> R.drawable.dice_6
            }

            Image(
                painter = painterResource(imageResource),
                contentDescription = result.toString()
            )
            //dp 尺寸以 4.dp 为增量进行更改
            Spacer(modifier = Modifier.height(16.dp))
            Button(onClick = { result = (1..6).random() }) {
                Text("Roll")
            }
        }
    }
}